package com.yundahh.u8c.util;

import com.yundahh.u8c.config.U8CConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.CharEncoding;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPatch;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

@Slf4j
public class HttpUtils {

    public static String sendGet(String url,  Map headers){
        log.debug("发送GET请求：{}",url);
        HttpClient client = HttpClientBuilder.create().build();

        final HttpGet request = new HttpGet(url);
        if(headers!=null){
            headers.forEach((k,v)->{
                request.addHeader(k.toString(),v.toString());
            });
        }
        HttpResponse execute = null;
        try {
            execute = client.execute(request);
            HttpEntity entity = execute.getEntity();
            String str = EntityUtils.toString(entity);
            log.debug("GET请求结果：{}",str);
            return str;
        } catch (IOException e) {
            log.debug("发送GET请求失败："+e.getMessage());
            throw new RuntimeException(e);
        }
    }



    /**
     * 发送一个post请求
     * @param url 请求地址
     * @param headers
     * @param json json数据体
     * @return
     */
    public static String sendPost(String url, Map headers, String json) throws IOException {
        int connectTimeout=30000;
        int socketTimeout=30000;
        log.debug("发送POST请求：{}，参数：{}",url,json);
        HttpClient client = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(url);
        if(headers!=null){
            headers.forEach((k,v)->{
                httpPost.addHeader(k.toString(),v.toString());
            });
        }
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(connectTimeout)
                .setConnectTimeout(connectTimeout).setSocketTimeout(socketTimeout).build();
        httpPost.setConfig(requestConfig);
        String resultString = "";
        CloseableHttpResponse response = null;
        try {
            httpPost.setHeader("Content-Type", "application/json");
            if(json!=null) {
                // 创建请求内容
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }
            // 执行http请求
            HttpResponse execute = client.execute(httpPost, HttpClientContext.create());
            if(execute.getEntity()==null){
                resultString="";
            }else{
                resultString = EntityUtils.toString(execute.getEntity(), "utf-8");
            }
            log.debug("POST请求结果:"+resultString);
        }  finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {

            }
        }
        return resultString;
    }

//    /**
//     * 发送PATCH请求
//     * @param url
//     * @param cookiesData
//     * @param json
//     * @return
//     */
//    public String sendPatch(String url, Map<String, String> cookiesData, String json){
//        log.info("发送Patch请求：{}，参数：{}",url,json);
//        HttpClient client = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
//        HttpPatch httpPatch = new HttpPatch(url);
//        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(sapSLConfig.getConnectTimeout())
//                .setConnectTimeout(sapSLConfig.getConnectTimeout()).setSocketTimeout(sapSLConfig.getSocketTimeout()).build();
//        httpPatch.setConfig(requestConfig);
//        String resultString = "";
//        HttpResponse response=null;
//        try {
//            httpPatch.setHeader("Content-Type", "application/json");
//            // 创建请求内容
//            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
//            httpPatch.setEntity(entity);
//            // 执行http请求
//            response =
//                    client.execute(httpPatch, HttpClientContext.create());
//            HttpEntity entity1 = response.getEntity();
//            if (entity1 != null) {
//                log.debug("PATCH - url:{}, response:{}", url, response);
//                return EntityUtils.toString(entity1, CharEncoding.UTF_8);
//            }
//        } catch (Exception e) {
//            log.info("发送Patch请求失败："+e.getMessage());
//            throw new RuntimeException(e);
//        } finally {
//
//        }
//        return "";
//    }
}
